package com.lh.struts.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.lh.jsp.urlparamEncoding.CharacterEncodingConstants;
import com.lh.log.log4j.LoggerImpl;
import com.lh.log.log4j.interfaces.Log;

public class CharsetEncodingFilter implements Filter {
	private static  Log logger = new LoggerImpl(CharsetEncodingFilter.class);
    private String charset = CharacterEncodingConstants.UTF8;  
    private FilterConfig config; 
	@Override
	public void destroy() {
		logger.debug("字符编码器"+config.getFilterName()+"被销毁");  
		charset = null;  
        config = null;  
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain fc) throws IOException, ServletException {
		 //设置请求响应字符编码  
        request.setCharacterEncoding(charset);  
        response.setCharacterEncoding(charset);  
        
        HttpServletRequest req = (HttpServletRequest)request;
        if(req.getMethod().equalsIgnoreCase("get"))  
        {  
            req = new RequestWrapperCharsetEncoding(req,charset);  
        }  
          
        logger.debug("----请求被"+config.getFilterName()+"过滤");  
        //执行下一个过滤器（如果有的话,否则执行目标servlet）  
        fc.doFilter(req, response);            
        logger.debug("----响应被"+config.getFilterName()+"过滤");
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		 this.config = config;  
         String charset = config.getInitParameter("charset");    
         if( charset != null && charset.trim().length() != 0)  
         {  
             this.charset = charset;  
         } 
         logger.debug("字符编码器"+config.getFilterName()+"初始化。");
	}

}
